package com.alvin.abp.domain.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.alvin.abp.domain.Bonus;
import com.alvin.abp.domain.Point;
import com.alvin.abp.domain.Status;
import com.alvin.abp.service.BonusService;
/**
 * Validation for bonus.
 * @author <a href="mailto:rex2.mj@gmail.com">Leo Meng</a>
 * @date $Date: Apr 5, 2013 $
 *
 */
@Component
public class BonusValidator implements Validator {
	
	@Autowired
	private BonusService bonusService;
	
	private static final int MIN_LENGTH = 12;

	public boolean supports(Class clazz) {
		return Bonus.class == clazz;
	}

	public void validate(Object target, Errors errors) {
		Bonus bonus = (Bonus) target;
		ValidationUtils.rejectIfEmpty(errors, "code", "error.required",
				new Object[] { new DefaultMessageSourceResolvable(
						"bonus.code") });
		
		if (!errors.hasErrors()) {
			if(bonus.getCode().length() < MIN_LENGTH){
				errors.rejectValue("code", "error.code.length",new Object[]{MIN_LENGTH},"");
			}else {
				Point point = bonusService.readPoint(bonus.getCode());
				if(point == null){
					errors.rejectValue("code", "error.code.invalid",new Object[]{bonus.getCode()},"");
				}else{
					Status status = point.getQrStatus();
					if(Status.QR_HAD_INTEGRAL.equals(status)){
						errors.rejectValue("code", "error.code.hasIntegral",new Object[]{bonus.getCode()},"");
					}else if(!bonusService.checkGoodStatus(bonus.getCode())){
						errors.rejectValue("code", "error.code.invalid",new Object[]{bonus.getCode()},"");
					}
				}
			}
			
		}
		
	}
	
}
